package com.example.wearing.find;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.javabean.Post;
import com.example.wearing.tools.BitmapBinder;
import com.example.wearing.tools.ImageUtil;
import com.example.wearing.tools.PostAdapter;
import com.example.wearing.tools.RefreshableView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.ByteArrayOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class FindFragment extends Fragment implements Runnable, AdapterView.OnItemClickListener{

    private FindViewModel mViewModel;
    FloatingActionButton fab;
    private ImageView postImg;
    private static final String TAG = "FindFragment";
    private Handler handler;
    private ArrayList<Post> postList = new ArrayList<>();
    private ListView postListView;
    private ProgressBar bar;
    private TextView nodata;
    private RefreshableView refreshableView;
    private String jdbcUrl ,jdbcUser, jdbcPassword;


    public static FindFragment newInstance() {
        return new FindFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.find_fragment, container, false);
        fab = view.findViewById(R.id.addPostBtn);
        postImg = view.findViewById(R.id.postImg);
        postListView =view.findViewById(R.id.postList);
        bar = view.findViewById(R.id.progressBar);
        nodata = view.findViewById(R.id.nodataText);
        refreshableView = view.findViewById(R.id.refreshable_view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(FindViewModel.class);
        // TODO: Use the ViewModel

        //从SharedPreferences中获取用户名
        SharedPreferences sp = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(getActivity());
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

        //悬浮按钮
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //进入发布帖子页面
                Intent addPostIntent = new Intent(getActivity(), AddPostActivity.class);
                startActivity(addPostIntent);
            }
        });

        //查询所有帖子并设置adapter显示
        searchAndAdapter();

        //设置下拉刷新
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
             @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
             @Override
             public void onRefresh() {
                 try {
                     Thread.sleep(3000);//线程休眠3s
                     postList.clear();//清空list内容
                     run();//重新执行搜索函数

                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 refreshableView.finishRefreshing();
             }
             }, 0);

        //设置帖子点击进入详情页
        postListView.setOnItemClickListener(this);

    }


    //查询所有帖子
    public void searchAndAdapter(){
        
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");

                if(msg.what == 1){
                    //接收消息
                    int res = (int) msg.obj;
                    if(res == 1){
                        //查询帖子成功，并放入了List<Post>
                        Log.i(TAG, "done: 查询成功");
                        Toast.makeText(getActivity().getApplicationContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "handleMessage: 帖子数量:"+postList.size());

                        //设置adapter，显示列表
                        PostAdapter postAdapter = new PostAdapter(getActivity(),
                                R.layout.post_list,
                                postList);
                        postListView.setAdapter(postAdapter);

                    }else if(res == 2){
                        //查询帖子失败
                        Log.i(TAG, "done: 查询失败");
                        Toast.makeText(getActivity().getApplicationContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                    }

                    //切换显示状态
                    bar.setVisibility(View.GONE);
                    //没有获得数据时显示
                    refreshableView.setVisibility(View.VISIBLE);
                    postListView.setEmptyView(nodata);
                    postListView.setVisibility(View.VISIBLE);


                }
                super.handleMessage(msg);
            }
        };


        Thread thread = new Thread(this);
        thread.start();
    }

    //点击列表中内容，触发函数
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Object itemStPosition = postListView.getItemAtPosition(position);

        Post post = (Post) itemStPosition;
        String titleStr = post.getP_title();
        String detailStr = post.getP_detail();

        Log.i(TAG, "onItemClick: titleStr:"+titleStr);
        Log.i(TAG, "onItemClick: detailStr:"+detailStr);

        //将imgStr转化为bitmap__byte[]进行传输
        String imgStr = post.getP_img();
        Bitmap bitmap = ImageUtil.base64ToImage(imgStr);
        String userImgStr = post.getP_user_img();
        Bitmap userBitmap = ImageUtil.base64ToImage(userImgStr);

        //打开新窗口
        Intent detailIntent = new Intent(getActivity(), PostDetailActivity.class);
        Log.i(TAG, "onItemClick: postID:"+post.getP_id());
        detailIntent.putExtra("postID", post.getP_id());
        detailIntent.putExtra("postTitle", titleStr);
        detailIntent.putExtra("postDetail", detailStr);
        detailIntent.putExtra("postTime", post.getP_time());
        detailIntent.putExtra("postUser",post.getP_user());
        detailIntent.putExtra("postLikeNum", post.getP_likeNum());
        detailIntent.putExtra("postReplyNum",post.getP_replyNum());

        Bundle bundle = new Bundle();
        bundle.putBinder("postImg", new BitmapBinder(bitmap));
        bundle.putBinder("postUserImg", new BitmapBinder(userBitmap));
        detailIntent.putExtras(bundle);

        startActivity(detailIntent);

    }

    //创建线程类，实现Runnable接口，用于查询所有帖子
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void run() {
        try {
            Log.i(TAG, "run: 1111");
            Class.forName("com.mysql.jdbc.Driver");
            Log.i(TAG, "run: 222");
            Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
            Log.i(TAG, "run: 3333");
//            String sql = "select * from post";
            String sql = "select u_name, u_img, p_title, p_detail, p_time, p_img, p_likeNum, p_replyNum, p_id, p_uid from user, post where u_id=p_uid order by p_time DESC";
            Statement st = (Statement)cn.createStatement();

            int resCode;
            try {
                ResultSet rs = st.executeQuery(sql);
                System.out.println("连接数据库成功");

//                rs.last(); // 将光标移动到最后一行
//                int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
//                Log.i(TAG, "run: 帖子数量rowcount:"+rowCount);
//                rs.beforeFirst();//将光标移回首行

                //查询出数据，将其放在List<Post>中，使用adapter将其显示在列表里
                while (rs.next()){
                    Post post = new Post();
                    post.setP_id(rs.getInt("p_id"));
                    post.setP_uid(rs.getInt("p_uid"));
                    post.setP_img(rs.getString("p_img"));
                    post.setP_detail(rs.getString("p_detail"));
                    post.setP_title(rs.getString("p_title"));
                    post.setP_time(rs.getString("p_time"));
                    post.setP_likeNum(rs.getInt("p_likeNum"));
                    post.setP_replyNum(rs.getInt("p_replyNum"));

                    post.setP_user_img(rs.getString("u_img"));
                    post.setP_user(rs.getString("u_name"));
                    postList.add(post);

                }
                Log.i(TAG, "run: 查询出数据，将其放在List<Post>中");

                resCode = 1;
                rs.close();
            } catch (SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__"+e);
                e.printStackTrace();
                resCode = 2;
            }

            //发送消息
            Message msg = handler.obtainMessage(1, resCode);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---查询结果");

            st.close();
            cn.close();
        } catch (ClassNotFoundException | SQLException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        }
    }


}